package com.cindata

import com.cindata.dictionary.*
import com.cindata.dimension.YearLimitDimension

import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional

import org.springframework.security.access.annotation.Secured

@Secured(['isAuthenticated()'])
@Transactional
class AbnormalMortgageBatchController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def abnormalMortgageBatchService
    def springSecurityService

    def index() {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def name = params["name"]
        def disposeMethod = params["disposeMethod"]

        def user = User.findById(springSecurityService.principal.id)
        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList)
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and f.role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }
        //查询待处理的不良资产包
        def sql = "select f.batch from AbnormalMortgageBatchFlowStage f left join f.batch c   where f.stage.id = c.stage.id and f.id in (select f.flowStage.id from AbnormalMortgageBatchFlowStageRole f where f.teamRole.code = 'Approval'" + roleSql + ")"
        if(params['flag'] ){
            sql = " from AbnormalMortgageBatch c where 1=1 "
        }
        def queryParam = [:]
        if (name && name != "")
        {
          sql += " and c.name like :name "
          queryParam['name'] = "%" + name + "%"
        }
        if (disposeMethod && disposeMethod != "")
        {
          sql += " and c.disposeMethod =  :disposeMethod "
          queryParam['disposeMethod'] = disposeMethod
        }
        sql += " order by c.modifiedDate desc"
        def abnormalMortgageBatchList = AbnormalMortgageBatch.executeQuery(sql, queryParam, [max: max, offset: offset])
        def abnormalMortgageBatchCount = AbnormalMortgageBatch.executeQuery(sql, queryParam)

        respond abnormalMortgageBatchList, model:[abnormalMortgageBatchCount: abnormalMortgageBatchCount, params: params]
    }

    def show(AbnormalMortgageBatch abnormalMortgageBatch) {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def city = params["city"]
        def loansDuration = params["loansDuration"]
        def mortgageStatus = params["mortgageStatus"]
        def loansAmountStart = params["loansAmountStart"]
        def loansAmountEnd = params["loansAmountEnd"]
        def loansBalanceStart = params["loansBalanceStart"]
        def loansBalanceEnd = params["loansBalanceEnd"]
        def isNonPerformingLoan = params["isNonPerformingLoan"]
        def startDateStart = params["startDateStart"]
        def startDateEnd = params["startDateEnd"]
        def accountId = params["accountId"]
        def mortgageType = params["mortgageType"]
        def mortgagePattern = params["mortgagePattern"]
        def mortgageCategory = params["mortgageCategory"]
        def riskWarningLevel = params["riskWarningLevel"]
        def serialNumber = params["serialNumber"]

        def user = User.findById(springSecurityService.principal.id)
        def mortgageQueryParam = new HashMap()
        def mortgageSql = " from BatchMortgage bm where bm.abnormalMortgageBatch.id = ${abnormalMortgageBatch?.id} and bm.mortgage.account.id in " + Account.FilterAccountSql(user)

        def sql = " "
        if (city && city != "-1")
        {
            sql += " and bm.mortgage.account.city.zoneNumber = :city "
            mortgageQueryParam["city"] = city
        }
        if (loansDuration && loansDuration != "")
        {
            def yearList = YearLimitDimension.list()
            yearList.each {
                if (it?.label == loansDuration)
                {
                    def loansDurationMin = it.minValue
                    def loansDurationMax = it.maxValue
                    sql += " and bm.mortgage.loansDuration > :loansDurationMin and bm.mortgage.loansDuration<= :loansDurationMax "
                    mortgageQueryParam['loansDurationMin'] = loansDurationMin
                    mortgageQueryParam['loansDurationMax'] = loansDurationMax
                }
            }
        }
        if (mortgageStatus && mortgageStatus != "")
        {
            sql += " and bm.mortgage.mortgageStatus.id = :mortgageStatus "
            mortgageQueryParam['mortgageStatus'] = Long.parseLong(mortgageStatus)
        }
        if (loansAmountStart && loansAmountStart != '')
        {
            sql += "and bm.mortgage.loansAmount >= :loansAmountStart "
            mortgageQueryParam['loansAmountStart'] = new BigDecimal(loansAmountStart) * 10000
        }
        if (loansAmountEnd && loansAmountEnd != '')
        {
            sql += "and bm.mortgage.loansAmount <= :loansAmountEnd "
            mortgageQueryParam['loansAmountEnd'] = new BigDecimal(loansAmountEnd) * 10000
        }
        if (loansBalanceStart && loansBalanceStart != '')
        {
            sql += "and bm.mortgage.loansBalance >= :loansBalanceStart "
            mortgageQueryParam['loansBalanceStart'] = new BigDecimal(loansBalanceStart) * 10000
        }
        if (loansBalanceEnd && loansBalanceEnd != '')
        {
            sql += "and bm.mortgage.loansBalance <= :loansBalanceEnd "
            mortgageQueryParam['loansBalanceEnd'] = new BigDecimal(loansBalanceEnd) * 10000
        }
        if (isNonPerformingLoan && isNonPerformingLoan != "")
        {
            sql += " and bm.mortgage.isNonPerformingLoan = :isNonPerformingLoan "
            mortgageQueryParam['isNonPerformingLoan'] = Boolean.parseBoolean(isNonPerformingLoan)
        }
        if (startDateStart)
        {
            //中文日期转换
            def dateStart = DateUtil.GetDateBeginByDateStr(startDateStart)
            sql += "and bm.mortgage.startDate >=  :dateStart "
            mortgageQueryParam['dateStart'] = dateStart
        }
        if (startDateEnd)
        {
            //中文日期转换
            def dateEnd = DateUtil.GetNextDateBeginByDateStr(startDateEnd)
            sql += "and bm.mortgage.startDate <=  :dateEnd "
            mortgageQueryParam['dateEnd'] = dateEnd
        }
        if (accountId && accountId != "")
        {
            sql += " and bm.mortgage.account.id = :accountId "
            mortgageQueryParam['accountId'] = Long.parseLong(accountId)
        }
        if (mortgagePattern && mortgagePattern != "")
        {
            sql += " and bm.mortgage.mortgagePattern.id = :mortgagePattern "
            mortgageQueryParam['mortgagePattern'] = Long.parseLong(mortgagePattern)
        }
        if (mortgageType && mortgageType != "")
        {
            sql += " and bm.mortgage.mortgageType.id = :mortgageType "
            mortgageQueryParam['mortgageType'] = Long.parseLong(mortgageType)
        }
        if (mortgageCategory && mortgageCategory != "")
        {
            sql += " and bm.mortgage.mortgageCategory.id = :mortgageCategory "
            mortgageQueryParam['mortgageCategory'] = Long.parseLong(mortgageCategory)
        }
        if (riskWarningLevel && riskWarningLevel != "")
        {
            sql += " and bm.mortgage.riskWarningLevel.id = :riskWarningLevel "
            mortgageQueryParam['riskWarningLevel'] = Long.parseLong(riskWarningLevel)
        }
        if (serialNumber && serialNumber != "")
        {
            sql += " and bm.mortgage.serialNumber = :serialNumber "
            mortgageQueryParam['serialNumber'] = serialNumber
        }

        //def countSql = " select count(bm.id) from BatchMortgage bm where bm.abnormalMortgageBatch.id = ${abnormalMortgageBatch?.id} and bm.mortgage.account.id in " + Account.FilterAccountSql(user)
        // countSql += sql
        // sql += "order by e.contractNo desc "
        // mortgageSql += sql


        def countSql = " select count(bm.id) "
        mortgageSql += sql
        countSql += mortgageSql
        mortgageSql += "order by bm.mortgage.contractNo desc "

        def batchMortgageList = BatchMortgage.executeQuery(mortgageSql, mortgageQueryParam, [max: max, offset: offset])
        def batchMortgageCount = BatchMortgage.executeQuery(countSql, mortgageQueryParam)

        def accountManageAccountSql = " from Account o where o.id in  " + Account.FilterAccountSql(user)
        def accountManageAccountList = Account.executeQuery(accountManageAccountSql)

        //工作流
        def approveRoleFlag = false
        def editRoleFlag = false
        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList)
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }
        def flowStage = AbnormalMortgageBatchFlowStage.findByBatchAndStage(abnormalMortgageBatch, abnormalMortgageBatch?.stage)
        if (flowStage)
        {
            editRoleFlag = AbnormalMortgageBatchFlowStageRole.find("from AbnormalMortgageBatchFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.EDIT()?.id]) && true
            approveRoleFlag = AbnormalMortgageBatchFlowStageRole.find("from AbnormalMortgageBatchFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        }

        respond abnormalMortgageBatch, model:[batchMortgageList: batchMortgageList, batchMortgageCount: batchMortgageCount[0], accountManageAccountList: accountManageAccountList, params: params, editRoleFlag: editRoleFlag, approveRoleFlag: approveRoleFlag]
    }

    def create() {
        respond new AbnormalMortgageBatch(params)
    }

    @Transactional
    def save(AbnormalMortgageBatch abnormalMortgageBatch) {
        if (abnormalMortgageBatch == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (abnormalMortgageBatch.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond abnormalMortgageBatch.errors, view:'create'
            return
        }

        abnormalMortgageBatch.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'abnormalMortgageBatch.label', default: 'AbnormalMortgageBatch'), abnormalMortgageBatch.id])
                redirect abnormalMortgageBatch
            }
            '*' { respond abnormalMortgageBatch, [status: CREATED] }
        }
    }

    def edit(AbnormalMortgageBatch abnormalMortgageBatch) {
        respond abnormalMortgageBatch
    }

    @Transactional
    def update(AbnormalMortgageBatch abnormalMortgageBatch) {
        if (abnormalMortgageBatch == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (abnormalMortgageBatch.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond abnormalMortgageBatch.errors, view:'edit'
            return
        }

        abnormalMortgageBatch.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'abnormalMortgageBatch.label', default: 'AbnormalMortgageBatch'), abnormalMortgageBatch.id])
                redirect abnormalMortgageBatch
            }
            '*'{ respond abnormalMortgageBatch, [status: OK] }
        }
    }

    @Transactional
    def delete(AbnormalMortgageBatch abnormalMortgageBatch) {

        if (abnormalMortgageBatch == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        abnormalMortgageBatch.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'abnormalMortgageBatch.label', default: 'AbnormalMortgageBatch'), abnormalMortgageBatch.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'abnormalMortgageBatch.label', default: 'AbnormalMortgageBatch'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    @Transactional
    def batchSave(AbnormalMortgageBatch abnormalMortgageBatch) {

        abnormalMortgageBatch.save()

        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def city = params["city"]
        def loansDuration = params["loansDuration"]
        def mortgageStatus = params["mortgageStatus"]
        def loansAmountStart = params["loansAmountStart"]
        def loansAmountEnd = params["loansAmountEnd"]
        def loansBalanceStart = params["loansBalanceStart"]
        def loansBalanceEnd = params["loansBalanceEnd"]
        def isNonPerformingLoan = params["isNonPerformingLoan"]
        def startDateStart = params["startDateStart"]
        def startDateEnd = params["startDateEnd"]
        def accountId = params["accountId"]
        def mortgageType = params["mortgageType"]
        def mortgagePattern = params["mortgagePattern"]
        def mortgageCategory = params["mortgageCategory"]
        def riskWarningLevel = params["riskWarningLevel"]

        def user = User.findById(springSecurityService.principal.id)
        def mortgageQueryParam = new HashMap()
        def mortgageSql = " from Mortgage e where e.account.id in " + Account.FilterAccountSql(user)

        def sql = " "
        if (city && city != "-1")
        {
            sql += " and e.account.city.zoneNumber = :city "
            mortgageQueryParam["city"] = city
        }
        if (loansDuration && loansDuration != "")
        {
            def yearList = YearLimitDimension.list()
            yearList.each {
                if (it?.label == loansDuration)
                {
                    def loansDurationMin = it.minValue
                    def loansDurationMax = it.maxValue
                    sql += " and e.loansDuration > :loansDurationMin and e.loansDuration<= :loansDurationMax "
                    mortgageQueryParam['loansDurationMin'] = loansDurationMin
                    mortgageQueryParam['loansDurationMax'] = loansDurationMax
                }
            }
        }
        if (mortgageStatus && mortgageStatus != "")
        {
            sql += " and e.mortgageStatus.id = :mortgageStatus "
            mortgageQueryParam['mortgageStatus'] = Long.parseLong(mortgageStatus)
        }
        if (loansAmountStart && loansAmountStart != '')
        {
            sql += "and e.loansAmount >= :loansAmountStart "
            mortgageQueryParam['loansAmountStart'] = new BigDecimal(loansAmountStart) * 10000
        }
        if (loansAmountEnd && loansAmountEnd != '')
        {
            sql += "and e.loansAmount <= :loansAmountEnd "
            mortgageQueryParam['loansAmountEnd'] = new BigDecimal(loansAmountEnd) * 10000
        }
        if (loansBalanceStart && loansBalanceStart != '')
        {
            sql += "and e.loansBalance >= :loansBalanceStart "
            mortgageQueryParam['loansBalanceStart'] = new BigDecimal(loansBalanceStart) * 10000
        }
        if (loansBalanceEnd && loansBalanceEnd != '')
        {
            sql += "and e.loansBalance <= :loansBalanceEnd "
            mortgageQueryParam['loansBalanceEnd'] = new BigDecimal(loansBalanceEnd) * 10000
        }
        if (isNonPerformingLoan && isNonPerformingLoan != "")
        {
            sql += " and e.isNonPerformingLoan = :isNonPerformingLoan "
            mortgageQueryParam['isNonPerformingLoan'] = Boolean.parseBoolean(isNonPerformingLoan)
        }
        if (startDateStart)
        {
            //中文日期转换
            def dateStart = DateUtil.GetDateBeginByDateStr(startDateStart)
            sql += "and e.startDate >=  :dateStart "
            mortgageQueryParam['dateStart'] = dateStart
        }
        if (startDateEnd)
        {
            //中文日期转换
            def dateEnd = DateUtil.GetNextDateBeginByDateStr(startDateEnd)
            sql += "and e.startDate <=  :dateEnd "
            mortgageQueryParam['dateEnd'] = dateEnd
        }
        if (accountId && accountId != "")
        {
            sql += " and e.account.id = :accountId "
            mortgageQueryParam['accountId'] = Long.parseLong(accountId)
        }
        if (mortgagePattern && mortgagePattern != "")
        {
            sql += " and e.mortgagePattern.id = :mortgagePattern "
            mortgageQueryParam['mortgagePattern'] = Long.parseLong(mortgagePattern)
        }
        if (mortgageType && mortgageType != "")
        {
            sql += " and e.mortgageType.id = :mortgageType "
            mortgageQueryParam['mortgageType'] = Long.parseLong(mortgageType)
        }
        if (mortgageCategory && mortgageCategory != "")
        {
            sql += " and e.mortgageCategory.id = :mortgageCategory "
            mortgageQueryParam['mortgageCategory'] = Long.parseLong(mortgageCategory)
        }
        if (riskWarningLevel && riskWarningLevel != "")
        {
            sql += " and e.riskWarningLevel.id = :riskWarningLevel "
            mortgageQueryParam['riskWarningLevel'] = Long.parseLong(riskWarningLevel)
        }

        def countSql = " select count(e.id) from Mortgage e where e.account.id in " + Account.FilterAccountSql(user)

        countSql += sql
        sql += "order by e.contractNo desc "
        mortgageSql += sql

        def mortgageList = Mortgage.executeQuery(mortgageSql, mortgageQueryParam)

        mortgageList?.each {
          def batchMortgage = new BatchMortgage(mortgage: it)
          abnormalMortgageBatch.addToMortgages(batchMortgage)
        }

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'abnormalMortgageBatch.label', default: 'AbnormalMortgageBatch'), abnormalMortgageBatch.id])
                redirect action: "index", method: "GET",params:[flag:true]
            }
            '*' { respond abnormalMortgageBatch, [status: CREATED,flag:true] }
        }
    }

    //初始化工作流
    @Transactional
    def initWorkflow(AbnormalMortgageBatch abnormalMortgageBatch)
    {
      if (!abnormalMortgageBatch?.workflow)
      {
        flash.message = "请选择工作流"
        redirect action:'show',id:abnormalMortgageBatch?.id
        return
      }

      if (AbnormalMortgageBatchFlowStage.countByBatch(abnormalMortgageBatch) > 0)
      {
        flash.message = "工作流已执行"
        redirect action:'show',id:abnormalMortgageBatch?.id
        return
      }

      abnormalMortgageBatchService.initAbnormalMortgageBatchFlowStage(abnormalMortgageBatch,abnormalMortgageBatch?.workflow)
      abnormalMortgageBatch.isInitWorkFlow = true
      abnormalMortgageBatch.save(flush:true)
      redirect action:'show',id:abnormalMortgageBatch?.id
    }

    // 不良资产包流程推进
    @Transactional
    def approve(AbnormalMortgageBatch abnormalMortgageBatch)
    {
        def user = User.findById(springSecurityService.principal.id)
        def flowStage = AbnormalMortgageBatchFlowStage.findByBatchAndStage(abnormalMortgageBatch, abnormalMortgageBatch?.stage)
        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList)
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }

        def approveRoleFlag = AbnormalMortgageBatchFlowStageRole.find("from AbnormalMortgageBatchFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        if(!approveRoleFlag)
        {
            flash.message = "权限校验失败"
            redirect action:'show',id:abnormalMortgageBatch?.id
            return
        }

        // 校验是否提交备注
        def comment = Comment.findByAbnormalMortgageBatchAndAbnormalMortgageBatchStage(abnormalMortgageBatch, abnormalMortgageBatch?.stage)
        if(!comment)
        {
            flash.message = "未提交审批意见"
            redirect action:'show', id: abnormalMortgageBatch?.id
            return
        }

        def map = abnormalMortgageBatchService.approve(abnormalMortgageBatch)
        if(!map['flag'])
        {
            flash.message = map['message']
            redirect action:'show', id:abnormalMortgageBatch?.id
            return
        }

        redirect action: 'index'
    }

    @Transactional
    def reject(AbnormalMortgageBatch abnormalMortgageBatch)
    {
        def user = User.findById(springSecurityService.principal.id)
        def flowStage = AbnormalMortgageBatchFlowStage.findByBatchAndStage(abnormalMortgageBatch, abnormalMortgageBatch?.stage)
        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList)
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }

        def approveRoleFlag = AbnormalMortgageBatchFlowStageRole.find("from AbnormalMortgageBatchFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        if(!approveRoleFlag)
        {
            flash.message = "权限校验失败"
            redirect action:'show', id:abnormalMortgageBatch?.id
            return
        }

        def comment = new Comment()
        comment.abnormalMortgageBatch = abnormalMortgageBatch
        comment.abnormalMortgageBatchStage = abnormalMortgageBatch?.stage
        comment.comment = params['comment']
        comment.save flush: true

        def canReject = abnormalMortgageBatchService.reject(abnormalMortgageBatch)
        if (canReject)
        {
            redirect action: 'index'
        }
        else
        {
            flash.message = "对不起，无权限拒绝"
            redirect action:'show', id: abnormalMortgageBatch?.id
            return
        }
    }

    @Transactional
    def changeStatus(AbnormalMortgageBatch abnormalMortgageBatch)
    {
        abnormalMortgageBatch.status = "Failed"
        abnormalMortgageBatch.descriptionOfFailure = params['descriptionOfFailure']
        abnormalMortgageBatch.save flush: true

        redirect action: 'show', params: [id: abnormalMortgageBatch?.id]
    }

    @Transactional
    def disposalSave1()
    {
        def abnormalMortgageBatch = AbnormalMortgageBatch.findById(params['abnormalMortgageBatch'])
        def department = Department.findById(params['department'])
        abnormalMortgageBatch.disposalDepartment = department
        if (abnormalMortgageBatch.validate())
        {
            abnormalMortgageBatch.save flush: true
        }
        else
        {
            println abnormalMortgageBatch.errors
        }

        // def user = User.findById(springSecurityService.principal.id)
        // def flowStage = AbnormalMortgageBatchFlowStage.findByBatchAndStage(abnormalMortgageBatch, abnormalMortgageBatch?.stage)
        // def roleSql = ""
        // def roleList = UserRole.findAllByUser(user)*.role
        // if (roleList)
        // {
        //     String roleIdList = roleList*.id?.toString()
        //     roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        // }

        // def approveRoleFlag = AbnormalMortgageBatchFlowStageRole.find("from AbnormalMortgageBatchFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        // if(!approveRoleFlag)
        // {
        //     flash.message = "权限校验失败"
        //     redirect action:'show',params: [id: abnormalMortgageBatch?.id]
        //     return
        // }

        // def map = abnormalMortgageBatchService.approve(abnormalMortgageBatch)
        // if(!map['flag'])
        // {
        //     flash.message = map['message']
        //     redirect action: 'show', params: [id: abnormalMortgageBatch?.id]
        //     return
        // }

        // redirect action: 'show', params: [id: abnormalMortgageBatch?.id]

        redirect url: request.getHeader('referer')
    }

    def disposalAsign(AbnormalMortgageBatch abnormalMortgageBatch)
    {
        params['targetUri'] = request.getHeader("referer")
        respond abnormalMortgageBatch, model: [params: params]
    }

    @Transactional
    def disposalAsignSave(AbnormalMortgageBatch abnormalMortgageBatch)
    {
        if (abnormalMortgageBatch.validate())
        {
            abnormalMortgageBatch.save flush: true
        }
        else
        {
            println abnormalMortgageBatch.errors
        }

        // def user = User.findById(springSecurityService.principal.id)
        // def flowStage = AbnormalMortgageBatchFlowStage.findByBatchAndStage(abnormalMortgageBatch, abnormalMortgageBatch?.stage)
        // def roleSql = ""
        // def roleList = UserRole.findAllByUser(user)*.role
        // if (roleList)
        // {
        //     String roleIdList = roleList*.id?.toString()
        //     roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        // }

        // def approveRoleFlag = AbnormalMortgageBatchFlowStageRole.find("from AbnormalMortgageBatchFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        // if(!approveRoleFlag)
        // {
        //     flash.message = "权限校验失败"
        //     redirect action: 'show', params: [id: abnormalMortgageBatch?.id]
        //     return
        // }

        // def map = abnormalMortgageBatchService.approve(abnormalMortgageBatch)
        // if(!map['flag'])
        // {
        //     flash.message = map['message']
        //     redirect action: 'show', params: [id: abnormalMortgageBatch?.id]
        //     return
        // }

        // redirect action: 'show', params: [id: abnormalMortgageBatch?.id]
        
        redirect url: params['targetUri']
    }
}
